use uuid::Uuid;
use mongodb::bson::{doc, from_document};
use mongodb::{bson::serde_helpers::uuid_as_binary, Database};
use crate::db::connect_to_db;
use anyhow::{Result, Context};
use teloxide::{prelude2::*,
             types::{InlineKeyboardButton, InlineKeyboardButtonKind, InlineKeyboardMarkup, ReplyMarkup},
};
use crate::user::{User, Collection, Element};
use futures::StreamExt;

use super::get_user;
pub async fn get_all_collections(bot: AutoSend<Bot>, m: Message) -> Result<()> {
    let user_id = m.from().context("NoneError")?.id;
    let user = get_user(user_id).await?;
    let db = connect_to_db().await?;
    let collections = get_all_user_collections(user.id, 0, &db).await?;
    let mut button_collections = Vec::with_capacity(51);
    for collection in collections{
        let button_name = format!(r#"name: {}
len: {}"#, collection.name(), collection.len());
        button_collections.push(vec![InlineKeyboardButton::new(
            button_name,
            InlineKeyboardButtonKind::CallbackData(format!("coll: {}", collection.id().to_hyphenated())),
        )])
    }

    button_collections.push(vec![
        InlineKeyboardButton::new(
            "<-",
            InlineKeyboardButtonKind::CallbackData("coll_page 0".to_string()),
        ),
        InlineKeyboardButton::new(
            "->",
            InlineKeyboardButtonKind::CallbackData("coll_page 2".to_string()),
        ),
    ]);
    bot.send_message(user_id,"All your collections:")
        .reply_markup(ReplyMarkup::InlineKeyboard(InlineKeyboardMarkup::new(
            button_collections.clone(),
        )))
        .await?;
    Ok(())
}

pub async fn get_all_user_collections(user_id: Uuid, pos: i32, db: &Database) -> Result<Vec<Collection>> {
    let coll = db.collection::<Collection>("usercollections");
    let match_aggr = doc! {
        "$match": {
        "user_id": user_id
        }
    };
    let unset_aggr = doc! {
        "$unset": "_id"
    };
    let unwind_aggr = doc! {
        "$unwind": "$collections"
    };
    let skip_aggr = doc! {
        "$skip": pos
    };
    let limit_aggr = doc! {
      "$limit": 50_i32
    };
    let pipeline = [
        match_aggr,
        unset_aggr,
        unwind_aggr,
        skip_aggr,
        limit_aggr,
    ];
    let mut cursor = coll.aggregate(pipeline, None).await?;
    let mut posts = Vec::with_capacity(50);
    while let Some(collection) = cursor.next().await {
        posts.push(from_document::<Collection>(collection?)?)
    }
    Ok(posts)
}
